package com.jt.www.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.jt.www.common.service.CorrectService;
import com.jt.www.common.service.PolicyAttributeService;
import com.jt.www.dao.mapper.correct.ApproveHistoryMapper;
import com.jt.www.dao.mapper.correct.CorrectMapper;
import com.jt.www.dao.mapper.correct.CorrectOrderPushMapper;
import com.jt.www.dao.mapper.offline.OfflineEndorseMapper;
import com.jt.www.dao.mapper.offline.OfflinePolicyMapper;
import com.jt.www.domain.enums.common.IsDeletedEnum;
import com.jt.www.domain.enums.common.IsOrNotEnum;
import com.jt.www.domain.enums.common.PushStatusEnum;
import com.jt.www.domain.enums.common.YesOrNoEnum;
import com.jt.www.domain.po.OfflineEndorse;
import com.jt.www.domain.po.OfflinePolicy;
import com.jt.www.enums.*;
import com.jt.www.enums.issue.AppStatusEnum;
import com.jt.www.exception.BizException;
import com.jt.www.model.correct.ApproveHistoryEntity;
import com.jt.www.model.correct.CorrectOrderPushEntiy;
import com.jt.www.model.correct.CorrectRecordEntity;
import com.jt.www.model.correct.RectifyUpdateEntiy;
import com.jt.www.model.correct.vo.ApproveParam;
import com.jt.www.model.correct.vo.CorrectionVoucherStatusVO;
import com.jt.www.model.correct.vo.EndorsementRectifyVO;
import com.jt.www.model.param.endorse.AppDetailProParam;
import com.jt.www.model.policyattribute.vo.PlicyClassVO;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.reps.GenericResponse;
import com.jt.www.model.reps.ResponseData;
import com.jt.www.model.torectify.vo.CorrectListParam;
import com.jt.www.model.torectify.vo.IntertemporalParam;
import com.jt.www.model.torectify.vo.RectifyUpdateDetailQo;
import com.jt.www.model.torectify.vo.RectifyUpdateQo;
import com.jt.www.model.vo.CommonUpdateDetailQo;
import com.jt.www.model.vo.CommonUpdateQo;
import com.jt.www.model.vo.endorse.AppDetailProVo;
import com.jt.www.remote.BmsClient;
import com.jt.www.remote.IdgClient;
import com.jt.www.remote.PolClient;
import com.jt.www.remote.SttlManClient;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.CommonUtils;
import com.jt.www.util.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.jt.www.util.DateUtils.*;

@Service
public class CorrectServiceImpl implements CorrectService {

    public static final Logger log = LoggerFactory.getLogger(CorrectServiceImpl.class);

    @Resource
    CorrectMapper correctMapper;

    @Resource
    CorrectOrderPushMapper correctOrderPushMapper;

    @Resource
    InsClient insClient;

    @Resource
    PolClient polClient;

    @Autowired
    ApproveHistoryMapper approveHistoryMapper;
    @Resource
    BmsClient bmsClient;
    @Resource
    OfflinePolicyMapper offlinePolicyMapper;
    @Resource
    OfflineEndorseMapper offlineEndorseMapper;
    @Resource
    PolicyAttributeService policyAttributeService;
    @Autowired
    private IdgClient idgClient;

    @Autowired
    private SttlManClient sttlManClient;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void pushCorrect(CorrectRecordEntity param) {
        initCorrectRecord(param);
        if (correctMapper.insertUseGeneratedKeys(param) != 1) {
            throw new BizException("冲正信息保存失败");
        }
    }

    @Override
    public ResponseEntity isIntertemporal(String findCode, String correctNo,IntertemporalParam intertemporalParam) throws Exception {
        Date issueDate = intertemporalParam.getIssueDate();
        Date startDate = intertemporalParam.getStartDate();
        Integer orderType = intertemporalParam.getOrderType();
        if(StringUtils.isEmpty(correctNo) && issueDate==null && startDate==null && orderType == null)
            throw  new Exception("请检查入参");
        //定义跨期和倒签的map
        Map<String,String> map = new HashMap<>();
        map.put("isBackdating","false"); //是否倒签
        map.put("isInIntertemporal","false"); //是否跨期
        //如果orderType是批单,只需要判断签单日期是否在跨期区间内
        if(orderType.equals(OrderTypeEnum.ORDER.getCode())){
            if (issueDate.after(startDate)) {
                //自動覆蓋
                map.put("isBackdating", "true"); //签单日期是否晚于
            }
            if (!DateUtils.isSameMonth(new Date(), issueDate)) {
                //从业管里面获取跨期起期和止期  签单日期需要格式化成类似 ：202103
                GenericListResponse intertermporalDate = getIntertemporal(issueDate);
                if(intertermporalDate.getList()!=null){
                    //拿当前时间也就是录单时间，在业管返回的期间内，判断，如果在就不是跨期，如果不在就跨期
                    if (!isEffectiveDate(format_date_format_yyyy_mm_dd.parse(getCurrentDay()),  DateUtils.strToDate((String)((LinkedHashMap) intertermporalDate.getList().get(0)).get("fperiodStart")),
                            DateUtils.strToDate((String) ((LinkedHashMap) intertermporalDate.getList().get(0)).get("fperiodEnd")))) {
                        map.put("isInIntertemporal","true");
                    }
                }
            }
        }else{
            //  批单不需要判断保险起期   只需要判斷签单日期是否和当前日期月份一致,不一致就调用业管
            if (!DateUtils.isSameMonth(new Date(), issueDate)) {
                GenericListResponse intertermporalDate = getIntertemporal(issueDate);
                //从业管里面获取跨期起期和止期  签单日期需要格式化成类似 ：202103
                if(intertermporalDate.getList()!=null){
                    //拿当前时间也就是录单时间，在业管返回的期间内，判断，如果在就不是跨期，如果不在就跨期
                    if (!isEffectiveDate(format_date_format_yyyy_mm_dd.parse(getCurrentDay()),  DateUtils.strToDate((String)((LinkedHashMap) intertermporalDate.getList().get(0)).get("fperiodStart")),
                            DateUtils.strToDate((String) ((LinkedHashMap) intertermporalDate.getList().get(0)).get("fperiodEnd")))) {
                        //自動覆蓋
                        map.put("isInIntertemporal","true");
                    }
                }
            }
        }
        return GenericDataResponse.okWithData(map);
    }

    public GenericListResponse getIntertemporal(Date issueDate) throws Exception {
        String fperiod = DateUtils.converDateYm(issueDate);
        GenericListResponse intertermporalDate = bmsClient.getIntertemporal(fperiod);
        return intertermporalDate;
    }


    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateCorrect(CorrectRecordEntity param) {
        param.setUpdateTime(new Date());
        param.setBranchCode(param.getBranchCode());
        Example example = new Example(CorrectRecordEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("serialNo", param.getSerialNo());
        criteria.andEqualTo("id", param.getId());
        if (correctMapper.updateByExampleSelective(param, example) != 1) {
            throw new BizException("冲正信息修改失败");
        }
    }

    private CorrectRecordEntity initCorrectRecord(CorrectRecordEntity param) {
        Date now = new Date();
        //TODO：远程idg服务获取序列号
      /*  String conAgreementNo = "C" + String.valueOf(idgClient.nextId());
        param.setCorrectApplyNo(conAgreementNo);*/
        param.setCorrectStatus((Integer) CorrectStatusEnum.WAIT.getCode());
        param.setApproveStatus((Integer) CorrectApproveStatusEnum.TOBEAUDIT.getCode());
        param.setCreateByName(param.getCreateByName());
        param.setCreateBy(param.getCreateBy());
        param.setBranchCode(param.getBranchCode());
        param.setCreateTime(now);
        param.setUpdateTime(now);
        param.setSerialNo(UUID.randomUUID().toString());
        return param;
    }

    public boolean checkChannel(Long connectId, String sysChannel) {
        Example example = new Example(CorrectRecordEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", connectId);
        criteria.andEqualTo("sysChannel", sysChannel);
        return correctMapper.selectCountByExample(example) == 0;
    }

    @Override
    public void approve(String sysChannelCode, String correctNoId, ApproveParam approveParam, String issueType) {
        //查询当前审批流程信息
        if (StringUtils.isEmpty(sysChannelCode) || StringUtils.isEmpty(approveParam.getCorrectNo()) || StringUtils.isEmpty(correctNoId)) {
            throw new BizException("传入参数有误");
        }
        //根据投保单号和批单号查询主表记录状态
        CorrectRecordEntity correctRecordEntity = correctMapper.selectByPrimaryKey(correctNoId);
        try {
            approveAndSend(correctRecordEntity, approveParam, issueType);
        } catch (Exception e) {
            CorrectRecordEntity up = new CorrectRecordEntity();
            up.setId(correctRecordEntity.getId());
            correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.FAIL.getCode());
            correctMapper.updateByPrimaryKeySelective(correctRecordEntity);
            e.printStackTrace();
        }
    }

    public AppDetailProVo insAppDetailList(String appCode) {
        log.info("query insClient application 开始--" + appCode);
        AppDetailProVo detailVos = null;
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProParam p = new AppDetailProParam();
        p.setAppCode(appCode);
        p.setChannelCode("edu");    // 渠道编号
        try {
            appDetailPro = insClient.searchAppDetailPro(p);
            detailVos = appDetailPro.getBody().getData();
        } catch (Exception e) {
            log.error("调用ins服务失败,错误信息:{} 投保单号为:{} ", e, appCode);
            e.printStackTrace();
        }
        return detailVos;
    }

    @Override
    public ResponseEntity<GenericResponse> isRecordAppCode(String appCode) {
        //根据投保单号查询是否是我学保项目
        AppDetailProVo appDetailProVo = insAppDetailList(appCode);
        //查询渠道我学保产品编码
        List<PlicyClassVO> policyAttributes = null;
        String productTypeList = null;
        try {
            policyAttributes = policyAttributeService.getProInfo("wxb", "2", "0");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (policyAttributes != null && policyAttributes.size() > 0) {
            productTypeList = policyAttributes.stream().map(PlicyClassVO::getCode).collect(Collectors.joining(","));
        }
        if (appDetailProVo == null) {
            return GenericResponse.ng("未查询到投保单数据");
        }
        if (productTypeList.contains(appDetailProVo.getProductCode())) {
            String applicationStatus = appDetailProVo.getApplicationStatus();
            if (applicationStatus.equals(AppStatusEnum.AS_10.getCode())) {
                return GenericResponse.ng("该投保单已出单请去我学保保单列表中进行批改操作");
            } else if (applicationStatus.equals(AppStatusEnum.AS_08.getCode()) || applicationStatus.equals(AppStatusEnum.AS_09.getCode()) || applicationStatus.equals(AppStatusEnum.AS_22.getCode())) {
                //可以进行操作
                return GenericResponse.ok();
            } else {
                return GenericResponse.ng("该投保单是" + AppStatusEnum.getEnumByCode(applicationStatus).getDesc() + "状态,暂不支持冲正");
            }
        } else {
            return GenericResponse.ng("该投保单不是我学保产品,暂不支持冲正");
        }
    }

    @Override
    public ResponseEntity<GenericResponse> selectAppCodeStatus(String appCode) {
        AppDetailProVo appDetailProVo = insAppDetailList(appCode);
        String applicationStatus = appDetailProVo.getApplicationStatus();
        List status = Arrays.stream(new String[]{AppStatusEnum.AS_08.getCode(), AppStatusEnum.AS_09.getCode(), AppStatusEnum.AS_22.getCode()}).collect(Collectors.toList());
        if (!status.contains(applicationStatus)) {
            log.error("该投保单号:{} , 状态已变更,不能进行冲正操作", appCode);
            return GenericResponse.ng("该投保单状态已变更,冲正操作过期");
        }

        return GenericResponse.ok();
    }

    public void updateCorrectRecEntity(CorrectRecordEntity correctRecordEntity, ApproveParam approveParam) {
        CorrectRecordEntity up = new CorrectRecordEntity();
        up.setId(correctRecordEntity.getId());
        correctRecordEntity.setCorrectStatus(approveParam.getStatus());
        correctRecordEntity.setToExamineTime(new Date());
        correctRecordEntity.setToExamineUser(approveParam.getToExamineUser());
        correctRecordEntity.setToExamineUserCode(approveParam.getToExamineCode());
        if (correctMapper.updateByPrimaryKeySelective(correctRecordEntity) != 1) {
            throw new BizException("更新冲正数据状态失败");
        }
        ;
    }


    public void insertApprove(CorrectRecordEntity correctRecordEntity
            , ApproveParam approveParam) {
        //新增审核说明信息
        Date now = new Date();
        ApproveHistoryEntity approveHistoryEntity = new ApproveHistoryEntity();
        approveHistoryEntity.setUserName(approveParam.getToExamineUser());
        approveHistoryEntity.setUserCode(approveParam.getToExamineCode());
        approveHistoryEntity.setConnectId(correctRecordEntity.getId());
        approveHistoryEntity.setApproveContent(approveParam.getComment());
        approveHistoryEntity.setConnectType(correctRecordEntity.getCorrectType());
        approveHistoryEntity.setApproveResult(CommonUtils.getEnumMsgByCode(CorrectApproveStatusEnum.values(), approveParam.getStatus()));
        approveHistoryEntity.setCreateTime(new Date());
        approveHistoryEntity.setUpdateTime(new Date());
        if (approveHistoryMapper.insert(approveHistoryEntity) != 1) {
            throw new BizException("新增审核状态失败");
        }
        ;
    }


    public void updateCorrect(CorrectRecordEntity correctRecordEntity, ApproveParam approveParam) {
        updateCorrectRecEntity(correctRecordEntity, approveParam);
        //新增审核说明信息
        insertApprove(correctRecordEntity, approveParam);
    }

    public CorrectOrderPushEntiy approveAndSend(CorrectRecordEntity correctRecordEntity
            , ApproveParam approveParam, String issueType) throws Exception {
        //校验是否可以进行冲正
        checkNodeAuthority(correctRecordEntity, approveParam);
        //推送之前先更新状态
        updateCorrect(correctRecordEntity, approveParam);
        //审核通过远程调用
        CorrectOrderPushEntiy correctOrderPushEntiy = null;
        //状态为审核通过,远程调用投保中心
        if (correctRecordEntity.getCorrectStatus() == CorrectApproveStatusEnum.AUDITSUCESS.getCode()) {
            if (correctRecordEntity.getOrderType().equals(OrderTypeEnum.ORDER.getCode()) || correctRecordEntity.getOrderType().equals(OrderTypeEnum.ENDORSEMENT.getCode())) {
                if (correctRecordEntity.getCorrectType() == CorrectTypeEnum.ALETER.getCode()
                        || correctRecordEntity.getCorrectType() == CorrectTypeEnum.DELET.getCode()) {
                    log.info("correct_push 调用业管凭证检验 入参 typeCode is {} correctNo is {}", OrderTypeEnum.
                            getEnumByCode(correctRecordEntity.getOrderType()), correctRecordEntity.getCorrectNo());
                    String systemType = correctRecordEntity.getCorrectType().equals("1") ? "04" : "03";
                    GenericListResponse<CorrectionVoucherStatusVO> response = bmsClient.correctVoucherStatus(OrderTypeEnum.getEnumByCode(correctRecordEntity.getOrderType()).getBmsCode(), systemType, correctRecordEntity.getCorrectNo());
                    log.info("correct_push 业管调用返回 {}", JSON.toJSON(response));
                    if (response == null) {
                        correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.FAIL.getCode());
                        return saveInitOrderPush(correctRecordEntity, "修改费用业管校验熔断");
                    }
                    if (!response.getCode().equals("0000")) {
                        correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.FAIL.getCode());
                        return saveInitOrderPush(correctRecordEntity, "修改费用业管返回9999");
                    }
                    log.info("correct_push 判断返回内容 response.getTotal()) is {} CollectionUtils.isNotEmpty(response.getList()) is {}"
                            , response.getTotal(), CollectionUtils.isNotEmpty(response.getList()));
                    if (response.getTotal() != 0) {
                        log.info("correct_push 获取业管错误信息 response.getList().get(0).getRemark() is {}", response.getList().get(0).getRemark());
                        StringBuilder strb = new StringBuilder(response.getList().get(0).getRemark()).append(", 凭证号为: ");
                        for (CorrectionVoucherStatusVO el : response.getList()) {
                            strb.append(el.getVoucherNo()).append(" ");
                        }
                        correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.FAIL.getCode());
                        return saveInitOrderPush(correctRecordEntity, strb.toString());
                    }
                }

                //保单冲正
                if (OrderTypeEnum.ORDER.getCode() == correctRecordEntity.getOrderType()) {
                    correctOrderPushEntiy = pushCorrectOrder(correctRecordEntity
                            , approveParam, issueType);
                }
                //批单冲正
                if (OrderTypeEnum.ENDORSEMENT.getCode() == correctRecordEntity.getOrderType()) {
                    correctOrderPushEntiy = pushEndorsementCorrect(correctRecordEntity
                            , approveParam, issueType);
                }

            } else {
                //投保单需要调用修改接口,不调用业管
                String accountingType = CorrectTypeEnum.getInsOrderCodeByCode(correctRecordEntity.getCorrectType());
                CommonUpdateQo commonUpdateQo = new CommonUpdateQo();
                commonUpdateQo.setAppCode(correctRecordEntity.getCorrectNo());
                commonUpdateQo.setUserCode(correctRecordEntity.getToExamineUserCode());
                List<CommonUpdateDetailQo> commonUpdateDetailQos = createCommonUpdateQo(correctRecordEntity, accountingType);
                commonUpdateQo.setUpdateDetailQoList(commonUpdateDetailQos);
                log.info("调用投保中心修改投保信息入參 : {}", JSONObject.toJSON(commonUpdateQo));
                correctOrderPushEntiy = saveInitOrderPush(correctRecordEntity, JSON.toJSONString(commonUpdateQo));
                //组装投保单修改接口参数
                ResponseData responseData = insClient.commonUpdate("01", commonUpdateQo);
                correctOrderPushEntiy.setPushResult(responseData.getCode());
                if (responseData.getCode().equals(ErrorCode.SUCCESS_CODE_0000)) {
                    //投保单更新成功,修改冲正状态
                    correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.SUCCESS.getCode());
                } else {
                    correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.FAIL.getCode());
                    if (responseData.getCode().equals(ResultEnum.ERROR_CODE_9999)) {
                        log.error("投保中心返回错误信息:{}", responseData.getMsg());
                        correctOrderPushEntiy.setPushResult(ResultEnum.ERROR_CODE_9999);
                    } else {
                        correctOrderPushEntiy.setPushResult("调用远程接口返回错误码");
                    }
                }
            }
            if (correctOrderPushEntiy == null ||
                    correctOrderPushMapper.updateByPrimaryKeySelective(correctOrderPushEntiy) != 1) {
                log.error("更新数据失败");
            }
        } else {
            correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.RETURN.getCode());
        }
        //推送后更新
        if (correctMapper.updateByPrimaryKey(correctRecordEntity) != 1) {
            throw new BizException("更新冲正数据状态失败");
        }
        return null;
    }

    /*
     * 封装投保单修改数据
     * @Author xq.wu
     * @Date 13:46 2020/10/10
     * @Param [correctRecordEntity, accountingType]
     * @return java.util.List<com.jt.www.model.vo.CommonUpdateDetailQo>
     **/
    private List<CommonUpdateDetailQo> createCommonUpdateQo(CorrectRecordEntity correctRecordEntity, String accountingType) {
        //00保险起期、01保险止期、08投保人名称、12被保人名称 15被保人地址、
        // 17投保人身份证、18投保人性别、19投保人出生日期、21被保人身份证、22被保人性别、23被保人出生日期、35.学校名称
        //36投保单省编码、37投保单市编码、38投保单县编码、39投保单省名称、40投保单市名称、41投保单县名称、42被保人省编码、43被保人市编码、44被保人县编码
        String correctContent = correctRecordEntity.getCorrectContent();
        Map<String, String> maps = (Map) JSON.parse(correctContent);
        System.out.println(maps);
        List list = new ArrayList<>(11);
        if (accountingType.equals(CorrectTypeEnum.NORMAL.getInsOrderCode())) {
            if (StringUtils.isNotEmpty(maps.get("startDate"))) {
                list.add(new CommonUpdateDetailQo("00", maps.get("startDate") + " 00:00:00"));
            }
            if (StringUtils.isNotEmpty(maps.get("endDate"))) {
                list.add(new CommonUpdateDetailQo("01", maps.get("endDate") + " 23:59:59"));
            }
            if (StringUtils.isNotEmpty(maps.get("holderName"))) {
                list.add(new CommonUpdateDetailQo("08", maps.get("holderName")));
            }
            if (StringUtils.isNotEmpty(maps.get("insuredName"))) {
                list.add(new CommonUpdateDetailQo("12", maps.get("insuredName")));
            }
            if (StringUtils.isNotEmpty(maps.get("holderIdNo"))) {
                list.add(new CommonUpdateDetailQo("17", maps.get("holderIdNo")));
            }
            if (StringUtils.isNotEmpty(maps.get("holderSex"))) {
                list.add(new CommonUpdateDetailQo("18", maps.get("holderSex")));
            }
            if (StringUtils.isNotEmpty(maps.get("holderBirthDay"))) {
                //前端无法精确到时分秒,需要单独处理
                String holderBirthDay = maps.get("holderBirthDay") + " 00:00:00";
                list.add(new CommonUpdateDetailQo("19", holderBirthDay));
            }
            if (StringUtils.isNotEmpty(maps.get("insuredIdNo"))) {
                list.add(new CommonUpdateDetailQo("21", maps.get("insuredIdNo")));
            }
            if (StringUtils.isNotEmpty(maps.get("insuredSex"))) {
                list.add(new CommonUpdateDetailQo("22", maps.get("insuredSex")));
            }
            if (StringUtils.isNotEmpty(maps.get("insuredBirthDay"))) {
                //前端无法精确到时分秒,需要单独处理
                String insuredBirthDay = maps.get("insuredBirthDay") + " 00:00:00";
                list.add(new CommonUpdateDetailQo("23", insuredBirthDay));
            }
            if (StringUtils.isNotEmpty(maps.get("schoolName"))) {
                //前端无法精确到时分秒,需要单独处理
                list.add(new CommonUpdateDetailQo("35", maps.get("schoolName")));
            }
            if (StringUtils.isNotEmpty(maps.get("provinceCode"))) {
                //前端无法精确到时分秒,需要单独处理
                list.add(new CommonUpdateDetailQo("36", maps.get("provinceCode")));
                list.add(new CommonUpdateDetailQo("42", maps.get("provinceCode")));
            }
            if (StringUtils.isNotEmpty(maps.get("cityCode"))) {
                //前端无法精确到时分秒,需要单独处理
                list.add(new CommonUpdateDetailQo("37", maps.get("cityCode")));
                list.add(new CommonUpdateDetailQo("43", maps.get("cityCode")));
            }
            if (StringUtils.isNotEmpty(maps.get("countyCode"))) {
                //前端无法精确到时分秒,需要单独处理
                list.add(new CommonUpdateDetailQo("38", maps.get("countyCode")));
                list.add(new CommonUpdateDetailQo("44", maps.get("countyCode")));
            }
            if (StringUtils.isNotEmpty(maps.get("provinceName"))) {
                //前端无法精确到时分秒,需要单独处理
                list.add(new CommonUpdateDetailQo("39", maps.get("provinceName")));
            }
            if (StringUtils.isNotEmpty(maps.get("cityName"))) {
                //前端无法精确到时分秒,需要单独处理
                list.add(new CommonUpdateDetailQo("40", maps.get("cityName")));
            }
            if (StringUtils.isNotEmpty(maps.get("countyName"))) {
                //前端无法精确到时分秒,需要单独处理
                list.add(new CommonUpdateDetailQo("41", maps.get("countyName")));
            }

        }
        return list;
    }


    /*
     *  查看截点是否可以审批
     * @Author xq.wu
     * @Date 15:06 2020/6/17
     * @Param [approveEntity, nodeId, user]
     * @return void
     **/
    private void checkNodeAuthority(CorrectRecordEntity correctRecordEntity, ApproveParam approveParam) {
        if (correctRecordEntity == null) {
            throw new BizException("找不到对应的审批节点");
        }

        //如果已经审核过则直接返回不处理
        if (correctRecordEntity.getCorrectStatus().equals(CorrectApproveStatusEnum.AUDITSUCESS.getCode())) {
            throw new BizException("该节点已审核通过,不能重复审核");
        }
        if (correctRecordEntity.getApproveStatus().equals(CorrectStatusEnum.SUCCESS.getCode())) {
            throw new BizException("冲正成功,不能继续此操作");
        }
    }


    /*
     *  远程调用批单中心冲正
     * @Author xq.wu
     * @Date 15:34 2020/6/15
     * @Param [correctRecordEntity, approveParam, user]
     * @return com.jt.www.model.correct.CorrectOrderPushEntiy
     **/
    private CorrectOrderPushEntiy pushEndorsementCorrect(CorrectRecordEntity correctRecordEntity
            , ApproveParam approveParam, String issueType) {
        //封装投保中心数据
        EndorsementRectifyVO endorsementRectifyVO = createEndorsementRectifyVO(correctRecordEntity, approveParam.getChannel());
        //保存调用远程接口状态，待返回
        CorrectOrderPushEntiy correctOrderPushEntiy = saveInitOrderPush(correctRecordEntity, JSON.toJSONString(endorsementRectifyVO));
        //调用远程接口
        log.info("invoke pol-svc to push correct info ");
        log.info("invoke params is {} ");
        //添加reSub_Token
     /*   String reSubToken = idgClient.getToken();
        FeignConfiguration.addHeader(FeignConfiguration.RE_SUB_TOKEN, reSubToken);*/
        ResponseEntity<GenericResponse> response = polClient.endorsementRectify(endorsementRectifyVO);
        log.info("invoke endorsementRectify return message {} ");
        initEndorResponse(response, correctOrderPushEntiy, correctRecordEntity, issueType);
        return correctOrderPushEntiy;
    }

    private void initEndorResponse(ResponseEntity<GenericResponse> response,
                                   CorrectOrderPushEntiy correctOrderPushEntiy, CorrectRecordEntity correctRecordEntity, String issueType) {
        correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.Submit.getCode());
        if (response == null) {
            correctOrderPushEntiy.setPushResult("调用远程接口熔断报错");
        }
        correctOrderPushEntiy.setPushResult(response.getBody().getCode());
        if (correctOrderPushEntiy.getPushResult().equals("0000")) {
            correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.SUCCESS.getCode());
            OfflineEndorse offlineEndorse = new OfflineEndorse();
            offlineEndorse.setEndorseNo(correctRecordEntity.getCorrectNo());
            OfflineEndorse endorse = offlineEndorseMapper.selectOne(offlineEndorse);
            if (endorse != null) {
                offlineEndorse.setId(endorse.getId());
                //判断是否是线上批单还是线下批单
                if (issueType.equals("02")) {
                    //判断是核算项目还是非核算项目
                    if (correctRecordEntity.getCorrectType() == CorrectTypeEnum.NORMAL.getCode()) {
                        if (correctRecordEntity.getSignTime() != null &&
                                org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.toYmdHms(correctRecordEntity.getSignTime()))) {
                            offlineEndorse.setInsureDate(correctRecordEntity.getSignTime());
                        }
                        if (correctRecordEntity.getStartTime() != null &&
                                org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.toYmdHms(correctRecordEntity.getStartTime()))) {
                            offlineEndorse.setStartDate(correctRecordEntity.getStartTime());
                        }
                        if (correctRecordEntity.getEndTime() != null &&
                                org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.toYmdHms(correctRecordEntity.getEndTime()))) {
                            offlineEndorse.setEndDate(correctRecordEntity.getEndTime());
                        }
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(correctRecordEntity.getCorrectNoAlter())) {
                            offlineEndorse.setEndorseNo(correctRecordEntity.getCorrectNoAlter());
                        }
                        offlineEndorseMapper.updateByPrimaryKeySelective(offlineEndorse);
                    } else if (correctRecordEntity.getCorrectType().equals(CorrectTypeEnum.ALETER.getCode())) {
                        offlineEndorse.setPremium(new BigDecimal(correctRecordEntity.getPremium()));
                        offlineEndorseMapper.updateByPrimaryKeySelective(offlineEndorse);
                    } else {
                        offlineEndorse.setIsDeleted(IsDeletedEnum.IS.getValue());
                        //线下需要修改渠道数据
                        offlineEndorseMapper.updateByPrimaryKeySelective(offlineEndorse);
                    }
                }
            } else {
                correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.FAIL.getCode());
                if (correctOrderPushEntiy.getPushResult().equals("9999")) {
                    correctOrderPushEntiy.setPushResult(response.getBody().getMsg());
                } else {
                    correctOrderPushEntiy.setPushResult("调用远程接口返回错误码");
                }
            }
        }
    }


    private EndorsementRectifyVO createEndorsementRectifyVO(CorrectRecordEntity correctRecordEntity, String channelCode) {
        EndorsementRectifyVO endorsementRectifyVO = new EndorsementRectifyVO();
        //TODO applyNo
        endorsementRectifyVO.setApplyNo(correctRecordEntity.getCorrectApplyNo());
        endorsementRectifyVO.setType(CorrectTypeEnum.getEndorsementCodeByCode(correctRecordEntity.getCorrectType()));
        endorsementRectifyVO.setRectifyTimes(queryTectifyTimes(correctRecordEntity.getCorrectNo()));
        endorsementRectifyVO.setSerialNo(correctRecordEntity.getSerialNo());
        endorsementRectifyVO.setApplyUserName(correctRecordEntity.getToExamineUser());
        endorsementRectifyVO.setChannelCode(channelCode);
        if (correctRecordEntity.getCorrectType() == CorrectTypeEnum.NORMAL.getCode()) {
            if (correctRecordEntity.getSignTime() != null &&
                    org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.toYmdHms(correctRecordEntity.getSignTime()))) {
                endorsementRectifyVO.setIssueDate(DateUtils.toYmdHms(correctRecordEntity.getSignTime()));
            }
            if (correctRecordEntity.getStartTime() != null &&
                    org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.converDate(correctRecordEntity.getStartTime()))) {
                endorsementRectifyVO.setStartDate(DateUtils.converDate(correctRecordEntity.getStartTime()) + " 00:00:00");
            }
            if (correctRecordEntity.getEndTime() != null &&
                    org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.converDate(correctRecordEntity.getEndTime()))) {
                endorsementRectifyVO.setEndDate(correctRecordEntity.getEndTime() == null ?
                        "" : DateUtils.converDate(correctRecordEntity.getEndTime()) + " 23:59:59");
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(correctRecordEntity.getCorrectNoAlter())) {
                endorsementRectifyVO.setEndorsementsNo(correctRecordEntity.getCorrectNoAlter());
            }
        } else if (correctRecordEntity.getCorrectType() == CorrectTypeEnum.ALETER.getCode()) {
            endorsementRectifyVO.setBatchPremium(new BigDecimal(correctRecordEntity.getPremium()));
        }
        return endorsementRectifyVO;
    }

    /**
     * 远程调用投保中心冲正
     *
     * @return com.jt.www.model.correct.CorrectOrderPushEntiy
     * @Author xq.wu
     * @Date 15:35 2020/6/15
     * @Param [correctRecordEntity, approveParam, user]
     **/
    private CorrectOrderPushEntiy pushCorrectOrder(CorrectRecordEntity correctRecordEntity
            , ApproveParam approveParam, String issueType) {
        String accountingType = CorrectTypeEnum.getInsOrderCodeByCode(correctRecordEntity.getCorrectType());
        //封装投保中心数据
        RectifyUpdateEntiy rectifyUpdateEntiy = new RectifyUpdateEntiy(
                createRectifyUpdateQo(correctRecordEntity, approveParam, approveParam.getChannel(), accountingType),
                CorrectTypeEnum.getInsOrderCodeByCode(correctRecordEntity.getCorrectType()));
        //保存调用远程接口状态，待返回
        CorrectOrderPushEntiy correctOrderPushEntiy = saveInitOrderPush(correctRecordEntity, JSON.toJSONString(rectifyUpdateEntiy));
        //调用远程接口
        log.info("invoke order-ins to push correct info ");
        log.info("invoke AccountingType  is {}, params is {} ", rectifyUpdateEntiy.getAccountingType(), rectifyUpdateEntiy.getRectifyUpdateQo());
        ResponseEntity<GenericResponse> response = insClient.rectifyUpdate(rectifyUpdateEntiy.getAccountingType(), rectifyUpdateEntiy.getRectifyUpdateQo());
        log.info("invoke order return message {} ");
        initResponse(response, correctOrderPushEntiy, correctRecordEntity, rectifyUpdateEntiy, issueType);
        return correctOrderPushEntiy;
    }

    private void initResponse(ResponseEntity<GenericResponse> response,
                              CorrectOrderPushEntiy correctOrderPushEntiy, CorrectRecordEntity correctRecordEntity, RectifyUpdateEntiy rectifyUpdateEntiy, String issueType) {
        correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.Submit.getCode());
        if (response == null) {
            correctOrderPushEntiy.setPushResult("调用远程接口熔断报错");
        }
        log.info("投保中心返回冲正返回数据: {} ", JSON.toJSON(response));
        correctOrderPushEntiy.setPushResult(response.getBody().getCode());
        log.info("获取到状态码为: {} ", correctOrderPushEntiy.getPushResult());
        if (correctOrderPushEntiy.getPushResult().equals("0000")) {
            correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.SUCCESS.getCode());
            //判断是否是线上出单还是线下出单
            OfflinePolicy offlinePolicy = new OfflinePolicy();
            //根据保单号查询到该条记录
            offlinePolicy.setPolicyNo(correctRecordEntity.getCorrectNo());
            offlinePolicy.setIsDeleted(IsOrNotEnum.NO.getValue());
            offlinePolicy.setPushStatus(PushStatusEnum.SUCCESS.getCode());
            OfflinePolicy policy = offlinePolicyMapper.selectOne(offlinePolicy);
            if (policy != null) {
                offlinePolicy.setId(policy.getId());
                if (issueType.equals("00")) {
                    //判断是核算项目还是非核算项目
                    if (correctRecordEntity.getCorrectType().equals(CorrectTypeEnum.NORMAL.getCode())) {
                        List<RectifyUpdateDetailQo> updateDetailQoList = rectifyUpdateEntiy.getRectifyUpdateQo().getUpdateDetailQoList();
                        for (RectifyUpdateDetailQo updateDetailQoLists : updateDetailQoList) {
                            String type = updateDetailQoLists.getType();
                            switch (type) {
                                case "00":
                                    offlinePolicy.setPolicyNo(updateDetailQoLists.getNewValue());
                                    offlinePolicyMapper.updateByPrimaryKeySelective(offlinePolicy);
                                    break;
                                case "01":
                                    Date insureDate = DateUtils.str2Date(updateDetailQoLists.getNewValue(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                                    offlinePolicy.setInsureDate(insureDate);
                                    offlinePolicyMapper.updateByPrimaryKeySelective(offlinePolicy);
                                    break;
                                case "02":
                                    Date startDate = DateUtils.str2Date(updateDetailQoLists.getNewValue(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                                    offlinePolicy.setStartDate(startDate);
                                    offlinePolicyMapper.updateByPrimaryKeySelective(offlinePolicy);
                                    break;
                                case "03":
                                    Date endDate = DateUtils.str2Date(updateDetailQoLists.getNewValue(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
                                    offlinePolicy.setEndDate(endDate);
                                    offlinePolicyMapper.updateByPrimaryKeySelective(offlinePolicy);
                                    break;
                                case "04":
                                    offlinePolicy.setHolderName(updateDetailQoLists.getNewValue());
                                    offlinePolicyMapper.updateByPrimaryKeySelective(offlinePolicy);
                                    break;
                                case "05":
                                    offlinePolicy.setInsuredName(updateDetailQoLists.getNewValue());
                                    offlinePolicyMapper.updateByPrimaryKeySelective(offlinePolicy);
                                    break;
                            }
                        }
                    } else if (correctRecordEntity.getCorrectType().equals(CorrectTypeEnum.ALETER.getCode())) {
                        offlinePolicy.setPremium(new BigDecimal(correctRecordEntity.getPremium()));
                        offlinePolicyMapper.updateByPrimaryKeySelective(offlinePolicy);
                    } else {
                        offlinePolicy.setIsDeleted(IsDeletedEnum.IS.getValue());
                        //线下需要修改渠道数据
                        offlinePolicyMapper.updateByPrimaryKeySelective(offlinePolicy);
                    }
                }
            }
        } else {
            correctRecordEntity.setApproveStatus((Integer) CorrectStatusEnum.FAIL.getCode());
            if (correctOrderPushEntiy.getPushResult().equals("9999")) {
                log.info("投保中心返回冲正错误: {} ", response.getBody().getMsg());
                correctOrderPushEntiy.setPushResult(response.getBody().getMsg());
            } else {
                correctOrderPushEntiy.setPushResult("调用远程接口返回错误码");
            }
        }
    }

    private CorrectOrderPushEntiy saveInitOrderPush(CorrectRecordEntity correctRecordEntity, String pushContent) {
        CorrectOrderPushEntiy correctOrderPushEntiy = new CorrectOrderPushEntiy();
        correctOrderPushEntiy.setPushResult("wait");
        correctOrderPushEntiy.setCorrectOrderId(correctRecordEntity.getId());
        correctOrderPushEntiy.setPushContent(pushContent);
        correctOrderPushEntiy.setCreateTime(new Date());
        if (correctOrderPushMapper.insertUseGeneratedKeys(correctOrderPushEntiy) != 1) {
            throw new BizException("保存推送记录出错");
        }
        //同时需要更新主表状态
        if (correctMapper.updateByPrimaryKey(correctRecordEntity) != 1) {
            throw new BizException("更新冲正数据状态失败");
        }
        CorrectOrderPushEntiy back = new CorrectOrderPushEntiy();
        back.setId(correctOrderPushEntiy.getId());
        return correctOrderPushEntiy;
    }

    private RectifyUpdateQo createRectifyUpdateQo(CorrectRecordEntity correctRecordEntity, ApproveParam approveParam, String channelCode, String accountingType) {
        RectifyUpdateQo rectifyUpdateQo = new RectifyUpdateQo();

        rectifyUpdateQo.setSerialNo(correctRecordEntity.getSerialNo());

        rectifyUpdateQo.setAppCode(correctRecordEntity.getCorrectApplyNo());

        rectifyUpdateQo.setChannelCode(channelCode);

        rectifyUpdateQo.setApplyUserCode(correctRecordEntity.getCreateBy());

        rectifyUpdateQo.setApplyUserName(correctRecordEntity.getCreateByName());

        rectifyUpdateQo.setApplyDate(correctRecordEntity.getCreateTime());

        rectifyUpdateQo.setAuditUserCode(approveParam.getToExamineCode());

        rectifyUpdateQo.setAuditUserName(approveParam.getToExamineUser());

        rectifyUpdateQo.setAuditDate(new Date());

        rectifyUpdateQo.setRectifyTimes(queryTectifyTimes(correctRecordEntity.getCorrectNo()));

        rectifyUpdateQo.setUpdateDetailQoList(createRectifyUpdateDetailQo(correctRecordEntity, accountingType));

        return rectifyUpdateQo;
    }


    private Integer queryTectifyTimes(String correctNo) {
        Example example = new Example(CorrectRecordEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("correctNo", correctNo);
        return correctMapper.selectCountByExample(example);
    }

    private List<RectifyUpdateDetailQo> createRectifyUpdateDetailQo(CorrectRecordEntity correctRecordEntity, String accountingType) {
        // 00保单号 / 01签单日期 / 02保险起期 / 03保险止期 / 04投保人名称 / 05被保人名称 / 06保费 / 07保单删除
        List list = new ArrayList<>(8);
        if (accountingType.equals(CorrectTypeEnum.NORMAL.getInsOrderCode())) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(correctRecordEntity.getCorrectNoAlter())) {
                list.add(new RectifyUpdateDetailQo("00", correctRecordEntity.getCorrectNoAlter()));
            }
            if (correctRecordEntity.getSignTime() != null && org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.toYmdHms(correctRecordEntity.getSignTime()))) {
                list.add(new RectifyUpdateDetailQo("01", DateUtils.toYmdHms(correctRecordEntity.getSignTime())));
            }
            if (correctRecordEntity.getStartTime() != null && org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.toYmdHms(correctRecordEntity.getStartTime()))) {
                list.add(new RectifyUpdateDetailQo("02", DateUtils.converDate(correctRecordEntity.getStartTime()) + " 00:00:00"));
            }
            if (correctRecordEntity.getEndTime() != null && org.apache.commons.lang3.StringUtils.isNotBlank(DateUtils.toYmdHms(correctRecordEntity.getEndTime()))) {
                list.add(new RectifyUpdateDetailQo("03", DateUtils.converDate(correctRecordEntity.getEndTime()) + " 23:59:59"));
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(correctRecordEntity.getPolicyHolderAlter())) {
                list.add(new RectifyUpdateDetailQo("04", correctRecordEntity.getPolicyHolderAlter()));
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(correctRecordEntity.getInsured())) {
                list.add(new RectifyUpdateDetailQo("05", correctRecordEntity.getInsured()));
            }
        } else {
            if (correctRecordEntity.getCorrectType() == CorrectTypeEnum.DELET.getCode()) {
                list.add(new RectifyUpdateDetailQo("07", ""));
            } else {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(correctRecordEntity.getPremium())) {
                    list.add(new RectifyUpdateDetailQo("06", correctRecordEntity.getPremium()));
                }
            }
        }
        return list;
    }


    @Override
    public CorrectRecordEntity queryById(Long id) {
        return correctMapper.selectByPrimaryKey(id);
    }

    public ApproveHistoryEntity queryApproveById(Long id) {
        //根据id查询附表
        ApproveHistoryEntity approveHistoryEntity = new ApproveHistoryEntity();
        approveHistoryEntity.setConnectId(id);
        List<ApproveHistoryEntity> approveHistoryEntities = approveHistoryMapper.select(approveHistoryEntity);
        ApproveHistoryEntity approveHistoryEntity1 = null;
        if (CollectionUtils.isNotEmpty(approveHistoryEntities)) {
            for (ApproveHistoryEntity approveHistoryEntity2 : approveHistoryEntities) {
                if (approveHistoryEntity1 == null || approveHistoryEntity2.getId() > approveHistoryEntity1.getId()) {
                    approveHistoryEntity1 = approveHistoryEntity2;
                }
            }
        }
        return approveHistoryEntity1;
    }

    /*
     *  检查投保单或者批单是否有审批中数据
     *  如果数量大于1,有审批数据,不能继续操作冲正
     * @Author xq.wu
     * @Date 17:31 2020/6/14
     * @Param [sysChannelCode, correctNo]
     * @return java.lang.Boolean
     **/
    @Override
    public Boolean isApproval(String sysChannelCode, String correctNo) {
        //根据投保单号或者批单号查询是否有数据
        Example example = new Example(CorrectRecordEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("correctNo", correctNo);
        List<CorrectRecordEntity> correctRecordEntity = correctMapper.selectByExample(example);
        if (correctRecordEntity.size() > 0) {
            for (CorrectRecordEntity correctRecordEntityList : correctRecordEntity) {
                if (correctRecordEntityList.getCorrectStatus().equals(CorrectApproveStatusEnum.TOBEAUDIT.getCode())) {
                    return false;
                }
            }
        }
        return true;
    }


    public GenericListResponse<CorrectionVoucherStatusVO> queryVoucher(String correctNo, String policyType, String correctType) {
        //根据类型和批单号/投保单号查询业管凭证状态
        if (StringUtils.isEmpty(correctNo) && StringUtils.isEmpty(policyType) && StringUtils.isEmpty(correctType)) {
            throw new BizException("参数为空,请确认");
        }
        String systemType = correctType.equals("1") ? "04" : "03";
        GenericListResponse<CorrectionVoucherStatusVO> response = bmsClient.correctVoucherStatus(OrderTypeEnum.getEnumByCode(Integer.parseInt(policyType)).getBmsCode(), systemType, correctNo);
        if (response == null) {
            throw new BizException("修改费用业管校验熔断");
        }
        if (!response.getCode().equals("0000")) {
            throw new BizException("修改费用业管返回9999");
        }
        if (response.getTotal() != 0) {
            log.info("correct_push 获取业管错误信息 response.getList().get(0).getRemark() is {}", response.getList().get(0).getRemark());
            StringBuilder strb = new StringBuilder(response.getList().get(0).getRemark()).append(", 凭证号为: ");
            for (CorrectionVoucherStatusVO el : response.getList()) {
                strb.append(el.getVoucherNo()).append(" ").append(el.getVoucherStatus());
            }
            throw new BizException(strb.toString());
        } else {
            response.setCode(GenericResponse.CODE_OK);
            return response;
        }
    }

    /*
     *  查询冲正列表
     * @Author xq.wu
     * @Date 16:25 2020/6/14
     * @Param [correctListParam]
     * @return com.github.pagehelper.Page
     **/
    @Override
    public Page queryByCondition(CorrectListParam correctListParam, String approveNot) {
        Example example = initExampe(correctListParam, approveNot);
        Page page = correctListParam.orderHandle();
        correctMapper.selectByExample(example);
        return page;
    }

    @Override
    public Page queryExamineByCondition(CorrectListParam correctListParam, String approveNot) {
        return queryByCondition(correctListParam, approveNot);
    }

    private Example initExampe(CorrectListParam correctListParam, String approveNot) {
        Example example = new Example(CorrectRecordEntity.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(correctListParam.getCorrectNo())) {
            criteria.andEqualTo("correctNo", correctListParam.getCorrectNo());
        }
        if (!StringUtils.isEmpty(String.valueOf(correctListParam.getOrderType()))) {
            criteria.andEqualTo("orderType", correctListParam.getOrderType());

        }
        if (!StringUtils.isEmpty(String.valueOf(correctListParam.getCorrectType()))) {
            criteria.andEqualTo("correctType", correctListParam.getCorrectType());

        }
        if (approveNot.equals(YesOrNoEnum.YES.getType())) {
            criteria.andEqualTo("correctStatus", CorrectApproveStatusEnum.TOBEAUDIT.getCode());
        } else {
            if (!StringUtils.isEmpty(String.valueOf(correctListParam.getCorrectStatus()))) {
                criteria.andEqualTo("correctStatus", correctListParam.getCorrectStatus());

            }
        }
        if (!StringUtils.isEmpty(String.valueOf(correctListParam.getApproveStatus()))) {
            criteria.andEqualTo("approveStatus", correctListParam.getApproveStatus());

        }
        if (!StringUtils.isEmpty(correctListParam.getSysChannelCode())) {
            criteria.andEqualTo("sysChannel", correctListParam.getSysChannelCode());

        }
        log.info("CorrectList query sysChannel is {}", correctListParam.getSysChannelCode());
        if (correctListParam.getStartTime() != null) {
            criteria.andGreaterThanOrEqualTo("createTime", correctListParam.getStartTime());
        }
        if (correctListParam.getEndTime() != null) {
            criteria.andLessThanOrEqualTo("createTime", correctListParam.getEndTime());
        }
        if (StringUtils.isNotEmpty(correctListParam.getBranchCode()) && !correctListParam.getBranchCode().equals("JT0000") && !correctListParam.getBranchCode().equals("000000")) {
            List<String> branchCodeList = Arrays.asList(correctListParam.getBranchCode().split(","));
            criteria.andIn("branchCode", branchCodeList);
        }
        example.setOrderByClause("create_time DESC");
        return example;
    }
}
